#include "clientnetengine.h"
#include "connectmsg.h"
#include "connectreplymsg.h"
#include "sourcemsg.h"

#include <QtDebug>
#include <QDataStream>
#include <QMutexLocker>

CClientNetEngine::CClientNetEngine(QAbstractSocket *pSock)
		: m_pSocket(pSock)
{
	connect(m_pSocket, SIGNAL(readyRead()), this, SLOT(onData()));
}

void CClientNetEngine::connectToServer(QString strUsername, QString strPassowrdHash)
{
	// create connection message:
	CConnectMsg msg;
	msg.setUsername(strUsername);
	msg.setPassword(strPassowrdHash);

	QDataStream ds(m_pSocket);
	QString strError;

	if (!msg.setMsg(ds, &strError))
	{
		emit commsError(QString("Error while trying to connect to server: '%1'").arg(strError));
		return;
	}
}

void CClientNetEngine::sendProject(QPair<QString, QStringList> theFileCollection, QString strConfigPayload)
{
	CSourceMsg theSourceMsg;

	theSourceMsg.addSourceFiles(theFileCollection.first, theFileCollection.second);
	theSourceMsg.setConfigPayload(strConfigPayload);

	QDataStream ds(m_pSocket);
	QString strError;

	if (!theSourceMsg.setMsg(ds, &strError))
	{
		emit commsError(QString("Error while trying to send project: '%1'").arg(strError));
		return;
	}
}

int CClientNetEngine::getMsgCount()
{
	QMutexLocker lock(&m_queueMutex);

	return m_messages.count();
}

CNetMsg *CClientNetEngine::getMessage()
{
	QMutexLocker lock(&m_queueMutex);

	return m_messages.takeFirst();
}

void CClientNetEngine::onData()
{
	static QMutex m;
	if (m.tryLock())
	{
		while (m_pSocket->bytesAvailable())
		{
			QString strError;
			QDataStream ds(m_pSocket);
			CNetMsg *pMsg = CNetMsg::getMsg(ds, &strError);

			if (pMsg)
			{
				queueMessage(pMsg);
			}
			else
			{
				emit commsError(QString("Error while waiting for server reply: '%1'").arg(strError));
			}
		}
		m.unlock();
	}
}

void CClientNetEngine::queueMessage(CNetMsg *p)
{
	qDebug("Queueing message");
	{
		QMutexLocker lock(&m_queueMutex);
		m_messages.enqueue(p);
	}
	emit newMessage();
}
